package com.hd.crdao.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.CarInfoListBean;
import com.hd.crdao.bean.FindStoreInfoBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.HeaderGridView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hss01248.dialog.StyledDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/6/30 0030
 */
public class ShopIndexActivity extends Activity implements View.OnClickListener {


    @BindView(R.id.allcarsource)
    Button mAllcarsource;
    @BindView(R.id.shopbusinesscard)
    Button mShopbusinesscard;
    @BindView(R.id.contactCarbusiness)
    Button mContactCarbusiness;
    @BindView(R.id.goback)
    ImageButton mGoback;
    @BindView(R.id.search_shopindex)
    LinearLayout mSearchShopindex;
    @BindView(R.id.storeLogo)
    CircleImageView mStoreLogo;
    @BindView(R.id.myshop_name)
    TextView mMyshopName;
    @BindView(R.id.myshop_location)
    TextView mMyshopLocation;
    @BindView(R.id.shopindex_tab)
    TextView mShopindexTab;
    @BindView(R.id.allcarsource_tab)
    TextView mAllcarsourceTab;
    @BindView(R.id.newarrival_tab)
    TextView mNewarrivalTab;
    @BindView(R.id.heedGridView)
    HeaderGridView mHeaderGridView;
    public FindStoreInfoBean.StoreInfoBean mStoreInfo;
    public List<CarInfoListBean> carInfoList;
    public ImageView mStoreImage;
    public String storeId;
    public String storeMobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopindex);
        ButterKnife.bind(this);
        initData();
        initEvent();

    }


    private void initData() {
        View headView = View.inflate(UIUtils.getContext(), R.layout.shopindex_headview, null);
        mStoreImage = (ImageView) headView.findViewById(R.id.storeImage);
        mHeaderGridView.addHeaderView(headView, null, false);
        mHeaderGridView.setHorizontalSpacing(8);
        mHeaderGridView.setVerticalSpacing(5);
        storeId = getIntent().getStringExtra("storeId");
        StyledDialog.buildLoading().setActivity(this).show();
        TelephonyManager telephonyManager = (TelephonyManager) this
                .getSystemService(Context.TELEPHONY_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        @SuppressLint("HardwareIds") final String deviceId = telephonyManager.getDeviceId();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ALog.d(deviceId);
                HashMap<String, String> map = new HashMap<>();
                map.put("appFlag", "true");
                map.put("storeId", storeId);
                map.put("visitsSource", deviceId);
                OkHttpUtils.post().url(Constants.FINDSTOREINFO_URL).params(map).build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show("网络开了个小差");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ALog.d(response);
                        FindStoreInfoBean findStoreInfoBean = new Gson().fromJson(response, FindStoreInfoBean.class);
                        if (findStoreInfoBean.getSuccess() == 0) {
                            mStoreInfo = findStoreInfoBean.getStoreInfo();
                            SPUtils.saveString("anotherBusinessId", findStoreInfoBean.getStoreInfo().getCarBusiness().getId());
                            mMyshopName.setText(mStoreInfo.getStoreName());
                            mMyshopLocation.setText(mStoreInfo.getStoreAddress());
                            storeMobile = mStoreInfo.getStoreMobile();
                            if (TextUtils.isEmpty(mStoreInfo.getStoreLogo())) {
                                mStoreLogo.setImageResource(R.drawable.logo_moren_2x);
                            } else {
                                GlideImageUtils.loadImage(Constants.IMAGEURL + mStoreInfo.getStoreLogo(),mStoreLogo);
                            }

                            if (TextUtils.isEmpty(mStoreInfo.getStoreImage())) {
                                mStoreImage.setImageResource(R.drawable.logo_moren_2x);
                            } else {
                                GlideImageUtils.loadImage(Constants.IMAGEURL + mStoreInfo.getStoreImage(),mStoreImage);
                            }
                            carInfoList = findStoreInfoBean.getCarInfoList();
                            mHeaderGridView.setAdapter(new MyPublishCarSoucrceAdapter(carInfoList));
                        } else {
                            MyToast.show(findStoreInfoBean.getMessage());
                        }
                    }
                });
                StyledDialog.dismissLoading();
            }
        }, 2000);

    }

    private void initEvent() {
        mShopbusinesscard.setOnClickListener(this);
        mContactCarbusiness.setOnClickListener(this);
        mAllcarsource.setOnClickListener(this);
        mAllcarsourceTab.setOnClickListener(this);
        mSearchShopindex.setOnClickListener(this);
        mNewarrivalTab.setOnClickListener(this);
        mGoback.setOnClickListener(this);
        mHeaderGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position = position - 2;
                CarInfoListBean carInfoListBean = carInfoList.get(position);
                Intent intent = new Intent(UIUtils.getContext(), CarDetailsActivity.class);
                intent.putExtra("carid", carInfoListBean.getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goback:
                onBackPressed();
                break;
            case R.id.shopbusinesscard:
                startActivity(new Intent(UIUtils.getContext(), ShopBusinessCardActivity.class));
                break;

            case R.id.contactCarbusiness:   //点击拨打电话
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + storeMobile));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;

            case R.id.allcarsource:
                jumpAllCarSource();
                break;

            case R.id.allcarsource_tab:
                jumpAllCarSource();
                break;
            case R.id.search_shopindex:
                jumpAllCarSource();
                break;
            case R.id.newarrival_tab:
                jumpAllCarSource();
                break;
        }
    }

    /**
     * 跳转到车商的车源中
     */
    public void jumpAllCarSource() {
        Intent intent = new Intent(UIUtils.getContext(), AllCarSourActivity.class);
        intent.putExtra("storeId", storeId);
        startActivity(intent);
    }


    private class MyPublishCarSoucrceAdapter extends MyBaseAdapter<CarInfoListBean> {
        MyPublishCarSoucrceAdapter(List<CarInfoListBean> dataSets) {
            super(dataSets);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(UIUtils.getContext(), R.layout.headgrideview_item, null);
                viewHolder.mIvPic = (ImageView) convertView.findViewById(R.id.ivPic);
                viewHolder.mTvDesc = (TextView) convertView.findViewById(R.id.tvDesc);
                viewHolder.mTvLocation = (TextView) convertView.findViewById(R.id.tvLocation);
                viewHolder.mSumPrice = (TextView) convertView.findViewById(R.id.sumPrice);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            CarInfoListBean carInfoListBean = mDataSets.get(position);
            viewHolder.mTvDesc.setText(carInfoListBean.getVehConfig().getVcTypenme());
            viewHolder.mSumPrice.setText(String.valueOf(carInfoListBean.getCiExpectprice()) + "万");
            String imageurl = carInfoListBean.getCoverPath();
            viewHolder.mTvLocation.setText(carInfoListBean.getCiPlatearea());
            if (TextUtils.isEmpty(imageurl)) {
                mStoreLogo.setImageResource(R.drawable.logo_moren_2x);
            } else {
                GlideImageUtils.loadImage(Constants.IMAGEURL + imageurl,R.drawable.logo_moren_2x,viewHolder.mIvPic);
            }
            return convertView;
        }


        class ViewHolder {
            ImageView mIvPic;
            TextView mTvDesc;
            TextView mTvLocation;
            TextView mSumPrice;
        }
    }
}